<template>
    <div>
        <!-- 卡片组件 -->
        <el-card shadow="never">
            <el-form ref="formRef" :model="form" label-width="160px" :rules="rules">
                <el-form-item>
                    <h2 class="font-bold text-base mb-1">AI设置</h2>
                    <el-text type="info" size="small">配置AI功能的相关参数，支持OpenAI兼容的API</el-text>
                </el-form-item>

                <!-- AI功能开关 -->
                <el-form-item label="启用AI功能" prop="aiEnabled">
                    <el-switch 
                        v-model="form.aiEnabled" 
                        inline-prompt 
                        :active-icon="Check" 
                        :inactive-icon="Close"
                    />
                    <div class="flex items-center ml-3">
                        <el-icon class="mr-2" color="#909399"><InfoFilled /></el-icon>
                        <el-text class="mx-1" type="info" size="small">开启后，前台将提供AI助手功能</el-text>
                    </div>
                </el-form-item>

                <!-- 分割线 -->
                <el-divider />

                <!-- API配置 -->
                <el-form-item>
                    <h3 class="font-bold text-sm mb-1">API配置</h3>
                </el-form-item>

                <el-form-item label="API地址" prop="aiApiUrl">
                    <el-input 
                        v-model="form.aiApiUrl" 
                        clearable 
                        placeholder="请输入AI API地址，如：https://api.openai.com/v1"
                    />
                    <div class="flex items-center">
                        <el-icon class="mr-2" color="#909399"><InfoFilled /></el-icon>
                        <el-text class="mx-1" type="info" size="small">支持OpenAI兼容格式的API地址</el-text>
                    </div>
                </el-form-item>

                <el-form-item label="API密钥" prop="aiApiKey">
                    <el-input 
                        v-model="form.aiApiKey" 
                        type="password" 
                        show-password
                        clearable 
                        placeholder="请输入API密钥"
                    />
                    <div class="flex items-center">
                        <el-icon class="mr-2" color="#909399"><InfoFilled /></el-icon>
                        <el-text class="mx-1" type="info" size="small">请确保API密钥有足够的调用权限</el-text>
                    </div>
                </el-form-item>

                <el-form-item label="模型名称" prop="aiModel">
                    <el-input 
                        v-model="form.aiModel" 
                        clearable 
                        placeholder="请输入模型名称，如：gpt-3.5-turbo, gpt-4, claude-3-sonnet"
                    />
                    <div class="flex items-center">
                        <el-icon class="mr-2" color="#909399"><InfoFilled /></el-icon>
                        <el-text class="mx-1" type="info" size="small">根据您使用的API提供商输入对应的模型名称</el-text>
                    </div>
                </el-form-item>

                <!-- 分割线 -->
                <el-divider />

                <!-- 高级配置 -->
                <el-form-item>
                    <h3 class="font-bold text-sm mb-1">高级配置</h3>
                </el-form-item>

                <el-form-item label="超时时间(秒)" prop="aiTimeout">
                    <el-input-number 
                        v-model="form.aiTimeout" 
                        :min="5" 
                        :max="300" 
                        controls-position="right"
                        style="width: 200px"
                    />
                    <div class="flex items-center ml-3">
                        <el-icon class="mr-2" color="#909399"><InfoFilled /></el-icon>
                        <el-text class="mx-1" type="info" size="small">API请求的超时时间，范围：5-300秒</el-text>
                    </div>
                </el-form-item>

                <el-form-item label="最大重试次数" prop="aiMaxRetries">
                    <el-input-number 
                        v-model="form.aiMaxRetries" 
                        :min="0" 
                        :max="10" 
                        controls-position="right"
                        style="width: 200px"
                    />
                    <div class="flex items-center ml-3">
                        <el-icon class="mr-2" color="#909399"><InfoFilled /></el-icon>
                        <el-text class="mx-1" type="info" size="small">API请求失败时的重试次数，范围：0-10次</el-text>
                    </div>
                </el-form-item>


                <!-- 配置示例说明 -->
                <el-form-item>
                    <el-alert
                        title="常见配置示例"
                        type="info"
                        :closable="false"
                    >
                        <template #default>
                            <div class="text-sm">
                                <p><strong>OpenAI官方:</strong></p>
                                <p>API地址: https://api.openai.com/v1</p>
                                <p>模型: gpt-3.5-turbo, gpt-4, gpt-4-turbo, gpt-4o</p>
                                <br>
                                <p><strong>Azure OpenAI:</strong></p>
                                <p>API地址: https://your-resource.openai.azure.com/openai/deployments/your-deployment</p>
                                <p>模型: gpt-35-turbo, gpt-4</p>
                                <br>
                                <p><strong>Claude API:</strong></p>
                                <p>API地址: https://api.anthropic.com/v1</p>
                                <p>模型: claude-3-haiku, claude-3-sonnet, claude-3-opus</p>
                                <br>
                                <p><strong>其他兼容服务:</strong></p>
                                <p>支持OpenAI格式的第三方API服务，直接输入对应的模型名称即可</p>
                            </div>
                        </template>
                    </el-alert>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" :loading="btnLoading" @click="onSubmit">保存设置</el-button>
                    <el-button @click="onTest" :loading="testLoading">测试连接</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Check, Close, InfoFilled } from '@element-plus/icons-vue'
import { getAiSettingsDetail, updateAiSettings } from '@/api/admin/aisettings'
import { showMessage } from '@/composables/util'

// 是否显示保存按钮的 loading 状态
const btnLoading = ref(false)
// 是否显示测试按钮的 loading 状态
const testLoading = ref(false)

// 表单引用
const formRef = ref(null)

// 表单对象
const form = reactive({
    aiEnabled: true,
    aiApiUrl: 'https://api.openai.com/v1',
    aiApiKey: '',
    aiModel: 'gpt-3.5-turbo',
    aiTimeout: 30,
    aiMaxRetries: 3,
    aiStreamEnabled: false
})

// 表单验证规则
const rules = reactive({
    aiApiUrl: [
        { required: true, message: 'API地址不能为空', trigger: 'blur' },
        { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
    ],
    aiApiKey: [
        { required: true, message: 'API密钥不能为空', trigger: 'blur' },
        { min: 10, message: 'API密钥长度至少10位', trigger: 'blur' }
    ],
    aiModel: [
        { required: true, message: '模型名称不能为空', trigger: 'blur' }
    ],
    aiTimeout: [
        { required: true, message: '超时时间不能为空', trigger: 'blur' },
        { type: 'number', min: 5, max: 300, message: '超时时间范围：5-300秒', trigger: 'blur' }
    ],
    aiMaxRetries: [
        { required: true, message: '最大重试次数不能为空', trigger: 'blur' },
        { type: 'number', min: 0, max: 10, message: '重试次数范围：0-10次', trigger: 'blur' }
    ]
})

// 页面加载时获取AI设置详情
onMounted(() => {
    fetchAiSettings()
})

// 获取AI设置详情
const fetchAiSettings = async () => {
    try {
        const res = await getAiSettingsDetail()
        if (res.success) {
            Object.assign(form, res.data)
        } else {
            showMessage(res.message || '获取AI设置失败', 'error')
        }
    } catch (error) {
        console.error('获取AI设置失败:', error)
        showMessage('获取AI设置失败', 'error')
    }
}

// 保存设置
const onSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        
        btnLoading.value = true
        
        const payload = {
            aiEnabled: form.aiEnabled,
            aiApiUrl: form.aiApiUrl,
            aiApiKey: form.aiApiKey,
            aiModel: form.aiModel,
            aiTimeout: form.aiTimeout,
            aiMaxRetries: form.aiMaxRetries,
            aiStreamEnabled: form.aiStreamEnabled
        }
        const res = await updateAiSettings(payload)
        
        if (res.success) {
            showMessage('AI设置保存成功')
            // 重新加载设置
            fetchAiSettings()
        } else {
            showMessage(res.message || '保存失败', 'error')
        }
    } catch (error) {
        console.error('保存AI设置失败:', error)
        showMessage('保存AI设置失败', 'error')
    } finally {
        btnLoading.value = false
    }
}

// 测试连接
const onTest = async () => {
    if (!form.aiApiUrl || !form.aiApiKey || !form.aiModel) {
        showMessage('请先填写完整的API配置信息', 'warning')
        return
    }
    
    testLoading.value = true
    
    try {
        // 这里可以调用后端的测试接口
        // 暂时模拟测试结果
        await new Promise(resolve => setTimeout(resolve, 2000))
        showMessage('API连接测试成功', 'success')
    } catch (error) {
        console.error('API连接测试失败:', error)
        showMessage('API连接测试失败', 'error')
    } finally {
        testLoading.value = false
    }
}
</script>

<style scoped>
.el-alert {
    margin-top: 10px;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-divider {
    margin: 20px 0;
}
</style>